package fi.foyt.cs.api;

import java.util.List;
import java.util.Locale;

import org.apache.commons.lang3.math.NumberUtils;
import org.restlet.data.Language;
import org.restlet.data.Preference;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

import fi.foyt.cs.Settings;

public class APIResource extends ServerResource {
  
  @Override
  protected void doInit() throws ResourceException {
    super.doInit();
  }

  protected String getStringAttribute(String name) {
    String value = (String) getRequest().getAttributes().get(name);
    return value;
  }

  protected Long getLongAttribute(String name) {
    return NumberUtils.createLong(getStringAttribute(name));
  }
  
  protected Integer getIntegerAttribute(String name) {
    return NumberUtils.createInteger(getStringAttribute(name));
  }
  
  protected Double getDoubleAttribute(String name) {
    return NumberUtils.createDouble(getStringAttribute(name));
  }
  
  protected Locale getLocale() {
    List<Locale> supportedLocales = Settings.getSupportedLocales();
    
    List<Preference<Language>> preferedLanguages = getRequest().getClientInfo().getAcceptedLanguages();
    for (Preference<Language> preferedLanguage : preferedLanguages) {
      Language langauge = preferedLanguage.getMetadata();
      
      for (Locale supportedLocale : supportedLocales) {
        if (supportedLocale.getLanguage().equals(langauge.getName()))
          return supportedLocale;
      }
    }
    
    return Settings.getDefaultLocale();
  }
}
